import axios from "axios";
import { mergeProps } from "../utils";

export default class Request {
  source;
  instance;
  interceptorRequest;
  constructor(config) {
    const cancelToken = axios.CancelToken;
    const source = cancelToken.source();
    this.source = source;
    this.config = mergeProps({ cancelToken: source.token }, config || {});
    // 创建axios实例
    this.instance = axios.create(this.config);
  }
  interceptorsRequest(interceptorRequest, errorHandler) {
    this.instance.interceptors.request.use(
      (request) => {
        return interceptorRequest(request);
      },
      (error) => {
        return errorHandler(error);
      }
    );
  }
  interceptorsResponse(interceptorResponse, errorHandler) {
    this.instance.interceptors.response.use(
      (response) => {
        return interceptorResponse(response);
      },
      (error) => {
        return errorHandler(error);
      }
    );
  }
  async send() {
    return this.instance.request(this.config);
  }
  cancel(msg) {
    this.source.cancel(msg);
  }
}
